from nltk.corpus import wordnet
import nltk.corpus.reader.wordnet

'''
noun
Created on Mar 30, 2014

@author: dan
'''

class noun(object):
    '''
    classdocs
    '''


    def __init__(self, plainword):
        '''
        Constructor
        '''

        self.value = plainword
        
        self.senses = \
          [nounsense(plainword,s) for s in wordnet.synsets(plainword)]
        
        '''Does naive testing of the noun to determine if we will consider it a
           named entity.'''
        '''If it's not in WordNet, assume that it's a Named Entity.
           If there is only 1 sense that isn't in the hierarchy, assume Named
           Entity (see Czechoslovakia in WordNet for an example)'''
        if ( not self.senses ) or \
           ( len(self.senses) == 1 and not self.senses[0].hypernyms() ):
            self.isNamedEntity = True
        else:
            self.isNamedEntity = False
        
        if self.isNamedEntity:
            self.senses = [wordnet.synset('person.n.01'),
                           wordnet.synset('organization.n.01'),
                           wordnet.synset('geographical_area.n.01')]

'''
nounsense
Created on Mar 30, 2014

A wrapper for a wordnet Synset object. This allows the nounsense
to behave as a Synset, but with added functions.

@author: dan
'''


class nounsense(object):
   def __init__(self, word, wnsynset):
      self._wnsense = wnsynset
      self._word = word

   '''This is the part where we give the outside world access to our Synset'''
   @property
   def name(self):
      return self._wnsense.name
   @property
   def definition(self):
      return self._wnsense.definition
   def hyponyms(self):
      return self._wnsense.hyponyms()
   def hypernyms(self):
      return self._wnsense.hypernyms()
   def member_meronyms(self):
      return self._wnsense.member_meronyms()
   def substance_meronyms(self):
      return self._wnsense.substance_meronyms()
   def part_meronyms(self):
      return self._wnsense.part_meronyms()


   '''This is the part where we give the nounsense an identity of its own'''

   '''Checks the wordnet hierarchy to see if this sense is a hyponym of
      any of the senses listed in hypernymsList'''
   def inheritsfrom(self, hypernymsList):
      if self.name in hypernymsList:
         return self._wnsense
      for path in self._wnsense.hypernym_paths():
         for hyper in hypernymsList:
            hypersense = wordnet.synset(hyper)
            if hypersense in path:
               return hypersense
      return False

   '''Checks the wordnet dictionary to see if words matching this sense contain
      a phrase.'''
   def ingloss(self, phrase):
      if self._wnsense.definition.rfind(phrase) > 0:
         return True
      else:
         return False
 
   def __repr__(self):
      return "%s('%s')" % (type(self).__name__, self._wnsense.name)
